<?php
class EmailTypeEnum
{
    const requestLife = 0;
    const receiveLife = 1;
    const receiveGift = 2;
}

class ShooterController extends Controller
{
    public function actionLoadSetting()
    {
        //{"key":"All"}
        $result = null;
        $jsonObj = Trans::readJsonPost();
        if (ShooterService::getInstance()->isNewVersionAvalible()) {
            ShooterService::getInstance()->updateSettingCache();
            ItemService::getInstance()->initItemList();
            ShooterService::getInstance()->setSettingVersion(Config::$settingVerison);
        }
        if (!isset($jsonObj->key)) {
            $result = array("status" => 0, "msg" => "key is needed");
        } else {
            $data = ShooterService::getInstance()->getSettingData($jsonObj->key);
            $result = array("status" => 1, "data" => $data);
        }
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }


    public function actionSubmitRecord()
    {
        //{"score":20,"deviceCode":"Axkas-192365-eeaeee","stage":3,"game_money":22}
        $result;
        $jsonObj = Trans::readJsonPost();
        if (!isset($jsonObj->game_money)) {
            $jsonObj->game_money = 0;
        }
        parent::llog(json_encode($jsonObj), "Shooter.SubmitRecord.PostData");
        if (isset($jsonObj->deviceCode) && isset($jsonObj->stage) && isset($jsonObj->score) && isset($jsonObj->level)) {
            $user = UserService::getInstance()->findByDevice($jsonObj->deviceCode);
            Trans::sendUrlGet("http://127.0.0.1:8081/g_shooter/User/DiSubmitRecord?momoid=".$user->id);
            if (isset($user)) {
                if (!isset($user->game_money)) {
                    $user->game_money = 0;
                }
                if (!isset($user->rank)) {
                    $user->rank = 0;
                }
                $user->rank = $user->rank + 10;
                $user->game_money = $user->game_money + (float)$jsonObj->game_money;
                if (!isset($user->final_stage)) {
                    $user->final_stage = 1;
                }
                $uScore = array();
                if (isset($user->higest_score)) {
                    if (is_object($user->higest_score) || is_array($user->higest_score)) {
                        $uScore = $user->higest_score;
                    } else {
                        $uScore = json_decode($user->higest_score);
                    }
                }
                $gameStage = "stage" . $jsonObj->stage;
                if (is_array($uScore)) {
                    if (isset($uScore[$gameStage])) {
                        if ((int)$uScore[$gameStage] < $jsonObj->score) {
                            $uScore[$gameStage] = $jsonObj->score;
                            UserService::getInstance()->setUserStageScore($gameStage, $jsonObj->deviceCode, $jsonObj->score);
                            UserService::getInstance()->setUserStageLevel($gameStage, $jsonObj->deviceCode, $jsonObj->level);
                        }
                    } else {
                        $uScore[$gameStage] = $jsonObj->score;
                    }
                } else {
                    if (isset($uScore->$gameStage)) {
                        if ((int)$uScore->$gameStage < $jsonObj->score) {
                            $uScore->$gameStage = $jsonObj->score;
                            UserService::getInstance()->setUserStageScore($gameStage, $jsonObj->deviceCode, $jsonObj->score);
                            UserService::getInstance()->setUserStageLevel($gameStage, $jsonObj->deviceCode, $jsonObj->level);
                        }
                    } else {
                        $uScore->$gameStage = $jsonObj->score;
                    }
                }
                $newGameStage = "stage" . ((int)$jsonObj->stage + 1);
                if ((int)$jsonObj->stage < Config::$stageCount) {
                    if ((int)$jsonObj->stage >= $user->final_stage) {
                        $user->final_stage = (int)$jsonObj->stage + 1;
                        if (is_array($uScore)) {
                            $uScore[$newGameStage] = 0;
                        } else {
                            $uScore->$newGameStage = 0;
                        }
                    } else {
                        if (is_array($uScore)) {
                            if (!isset($uScore[$newGameStage])) {
                                $uScore[$newGameStage] = 0;
                            }
                        } else {
                            if (!isset($uScore->$newGameStage)) {
                                $uScore->$newGameStage = 0;
                            }
                        }
                    }
                }
                $user->higest_score = json_encode($uScore);
                $user->save();
                $user->higest_score = json_decode($user->higest_score);
                $modelArr = $user->attributes;
                array_walk_recursive($modelArr, function (&$item, $key) {
                    if (is_numeric($item)) {
                        $item = (int)$item;
                    }
                });
                UserService::getInstance()->updateDeviceUKey($jsonObj->deviceCode, json_encode($modelArr));
                UserService::getInstance()->setUserRank($modelArr["device"], $modelArr["rank"]);
                $result = array("status" => 1, "user" => $modelArr);
            } else {
                $result = array("status" => 0, "msg" => "deviceCode not find");
            }

        } else {
            $result = array("status" => 0, "msg" => "need deviceCode,score,stage,level");
        }
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }

    public function actionGetFriendRank()
    {
        //{"dejaId":100032;"size":128,"deviceCode":"ASSASSSSSA"}
        $result = null;
        $jsonObj = Trans::readJsonPost();
        $size = 64;
        if (isset($jsonObj->size)) {
            $size = $jsonObj->size;
        }
        if (!isset($jsonObj->dejaId) || !isset($jsonObj->deviceCode)) {
            $result = array("status" => 0, "msg" => "dejaId is require");
        } else {
            $friendIds = UserService::getInstance()->getFriendIds($jsonObj->dejaId, $jsonObj->deviceCode);
//            if(is_array($friendIds) && count($friendIds)>0)
//            {
//                array_push($friendIds,$jsonObj->dejaId);
//            }
//            $getProfilesUrl = trim(Config::$public_apis['getProfiles'], '/');
//            $postData = array("user_ids" => $friendIds);
//            parent::llog(arrayToKV($postData), "UserService.getDejaModel.Deja.Postdata");
//            $resStr = UserService::getInstance()->requestDejaApi($getProfilesUrl, $postData, $jsonObj->deviceCode);
//            var_dump(json_encode($resStr));

            $friendsInfo = UserService::getInstance()->getFriendsInGamesFromDeja($friendIds, $jsonObj->deviceCode, $size);
            usort($friendsInfo, 'sortByRank');
            $result = array("status" => 1, "friendsInfo" => $friendsInfo, "count" => count($friendsInfo));
        }
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }

    public function actionGetFriendStageScore()
    {
        //{"dejaId":100032;"size":128,"deviceCode":"niuguangyuan_test_device_000001"}
        $result = null;
        $jsonObj = Trans::readJsonPost();
        $size = 64;
        if (isset($jsonObj->size)) {
            $size = $jsonObj->size;
        }
        if (isset($jsonObj->deviceCode)) {
            $u = UserService::getInstance()->getUserByDevice($jsonObj->deviceCode);
            $stagesScore = array();
            if (isset($u) && $u->deja_id > 0) {
                $friendIds = UserService::getInstance()->getFriendIds($u->deja_id, $jsonObj->deviceCode);
                if (!in_array($u->deja_id, $friendIds)) {
                    array_push($friendIds, $u->deja_id);
                }
                $friendsInfo = UserService::getInstance()->getFriendsInfoWithStage($friendIds, $jsonObj->deviceCode, $size);
                if (isset($friendsInfo) && is_array($friendsInfo) && count($friendsInfo) > 0) {
                    for ($i = 1; $i < 55; $i++) {
                        $keyT = "stage" . $i;
                        if (!isset($stagesScore[$keyT])) {
                            $stagesScore[$keyT] = array();
                        }
                    }
                    foreach ($friendsInfo as $friendInfo) {
                        $stages = $friendInfo->stages;
                        if (isset($stages)) {
                            foreach ($stages as $stage => $score) {
                                $tFriend = clone $friendInfo;
                                unset($tFriend->stages);
                                $tFriend->score = $score;
                                array_push($stagesScore[$stage], $tFriend);
                            }
                        }
                    }
                    foreach ($stagesScore as $key => $val) {
                        usort($val, 'sortByScore');
                        foreach ($val as $uInfo) {
                            $uInfo->level = UserService::getInstance()->getUserStageLevel($key, $uInfo->device);
                            unset($uInfo->device);
                        }
                        $stagesScore[$key] = $val;
                    }
                }
            }
            $result = array("status" => 1, "friendStageScore" => $stagesScore, "count" => count($stagesScore));
        } else {
            $result = array("status" => 0, "msg" => "deviceCode is require");
        }
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }


//    public function actionGetUserStageInfo()
//    {
//        //{"dejaId":100032;"size":128,"deviceCode":"niuguangyuan_test_device_000001"}
//        $result = null;
//        $jsonObj = Trans::readJsonPost();
//        $size = 64;
//        if (isset($jsonObj->size)) {
//            $size = $jsonObj->size;
//        }
//        if (isset($jsonObj->deviceCode)) {
//            $u = UserService::getInstance()->getUserByDevice($jsonObj->deviceCode);
//            if (isset($u)) {
//                $friendIds = array();
//                $userStageInfo = array();
//                if ($u->deja_id > 0) {
//                    $friendIds = UserService::getInstance()->getFriendIds($u->deja_id, $jsonObj->deviceCode);
//                    array_push($friendIds, $u->deja_id);
//                    $friendsInfo = UserService::getInstance()->getFriendsInfoWithStage($friendIds, $jsonObj->deviceCode, $size);
//                    $stagesScore = array();
//                    if (isset($friendsInfo) && is_array($friendsInfo) && count($friendsInfo) > 0) {
//                        foreach ($friendsInfo as $friendInfo) {
//                            $stages = $friendInfo->stages;
//                            if (isset($stages)) {
//                                foreach ($stages as $stage => $score) {
//                                    if (isset($stagesScore[$stage])) {
//                                        $tFriend = clone $friendInfo;
//                                        unset($tFriend->stages);
//                                        $tFriend->score = $score;
//                                        array_push($stagesScore[$stage], $tFriend);
//                                    } else {
//                                        $tFriend = clone $friendInfo;
//                                        unset($tFriend->stages);
//                                        $stagesScore[$stage] = array();
//                                        $tFriend->score = $score;
//                                        array_push($stagesScore[$stage], $tFriend);
//                                    }
//                                }
//                            }
//                        }
//                        foreach ($stagesScore as $key => $val) {
//                            usort($val, 'sortByScore');
//                            foreach ($val as $uInfo) {
//                                $uInfo->level = UserService::getInstance()->getUserStageLevelOld($uInfo->device, $key);
//                                if ($uInfo->id == $u->deja_id) {
//                                    unset($uInfo->id);
//                                    unset($uInfo->device);
//                                    unset($uInfo->name);
//                                    unset($uInfo->gender);
//                                    unset($uInfo->avatar);
//                                    unset($uInfo->avatar_head);
//                                    $userStageInfo[$key] = $uInfo;
//                                    break;
//                                }
//                            }
//                            $stagesScore[$key] = $val;
//                        }
//                    }
//                } else {
//                    if (isset($u->higest_score) && !empty($u->higest_score)) {
//                        var_dump($u->higest_score);
//                        if (is_string($u->higest_score)) {
//                            $u->higest_score = json_decode($u->higest_score);
//                        }
//                        foreach ($u->higest_score as $stage => $score) {
//                            $uInfo = new stdClass();
//                            $uInfo->score = $score;
//                            $uInfo->level = UserService::getInstance()->getUserStageLevel($jsonObj->deviceCode, $stage);
//                            $userStageInfo[$stage] = $uInfo;
//                        }
//                    }
//                }
//                $result = array("status" => 1, "userStageInfo" => $userStageInfo, "count" => count($userStageInfo), "final_stage" => (int)$u->final_stage);
//            } else {
//                $result = array("status" => 0, "msg" => "deviceCode is not found");
//            }
//        } else {
//            $result = array("status" => 0, "msg" => "deviceCode is require");
//        }
//        $this->renderPartial('json', array(
//            'jsonArr' => $result,
//            'postdata' => $jsonObj,
//        ));
//    }
    public function actionGetUserStageInfo()
    {
        //{"dejaId":100032;"size":128,"deviceCode":"niuguangyuan_test_device_000001"}
        $result = null;
        $jsonObj = new stdClass();
        $jsonObj->deviceCode="niuguangyuan_test_device_000001";
        $jsonObj->dejaId=100197;
        $size = 64;
        if (isset($jsonObj->size)) {
            $size = $jsonObj->size;
        }
        if (isset($jsonObj->deviceCode)) {
            $u = UserService::getInstance()->getUserByDevice($jsonObj->deviceCode);
            if (isset($u)) {
                $friendIds = array();
                $userStageInfo = array();
                foreach ($u->higest_score as $stage => $score) {
                    $uInfo = new stdClass();
                    $uInfo->score = $score;
                    $uInfo->level = UserService::getInstance()->getUserStageLevel($jsonObj->deviceCode, $stage);
                    $userStageInfo[] = $uInfo;
                }
                $result = array("data" => $userStageInfo);
            } else {
                $result = array("status" => 0, "msg" => "deviceCode is not found");
            }
        } else {
            $result = array("status" => 0, "msg" => "deviceCode is require");
        }
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }

    public function actionGetUserRankAround()
    {
        //{"deviceCode":"AAAAA8888-001","count":2,"size":128}
        $result = null;
        $usersInfo = array();
        $jsonObj = Trans::readJsonPost();
        $offset = 0;
        $count = 2;
        $size = 64;
        if (!isset($jsonObj->deviceCode)) {
            $result = array("status" => 0, "msg" => "need deviceCode");
        } else {
            if (isset($jsonObj->count)) {
                $count = $jsonObj->count;
            }
            if (isset($jsonObj->size)) {
                $size = $jsonObj->size;
            }
            $devices = UserService::getInstance()->getUserRank(0, 0);
            $devCount = count($devices);
            parent::llog(json_encode($devices), "Shooter.GetUserRankAround.All");
            if (is_array($devices) && ($devCount > $count * 2 + 1)) {
                $founded = array_search($jsonObj->deviceCode, $devices);
                $newDevices = array();
                $needCount = $count * 2 + 1;
                array_push($newDevices, $jsonObj->deviceCode);
                $needCount--;
                for ($i = 1; $i <= $count && ($founded - $i) >= 0; $i++) {
                    $inx = $founded - $i;
                    array_unshift($newDevices, $devices[$inx]);
                    $needCount--;
                }
                for ($j = 1; ($founded + $j) <= $devCount - 1 && $needCount > 0; $j++) {
                    $jnx = $founded + $j;
                    array_push($newDevices, $devices[$jnx]);
                    $needCount--;
                }
                if ($needCount > 0) {
                    for ($k = $count + 1; $needCount > 0; $k++) {
                        $knx = $founded - $k;
                        array_unshift($newDevices, $devices[$knx]);
                        $needCount--;
                    }
                }
                //parent::llog($founded, "Shooter.GetUserRankAround.founded");
                //parent::llog(json_encode($newDevices), "Shooter.GetUserRankAround.newDevices");
                $devices = $newDevices;
            }
            if (is_array($devices)) {
                $u = UserService::getInstance()->getUserByDevice($jsonObj->deviceCode);
                $friendIds = array();
                $deja_id = -1;
                if (isset($u)) {
                    $deja_id = $u->deja_id;
                }
                $friendIds = UserService::getInstance()->getFriendIds($deja_id, $jsonObj->deviceCode);
                $usersInfo = UserService::getInstance()->getUsersRankFromDevices($devices, $size, $friendIds);
            }
            $result = array("status" => 1, "usersInfo" => $usersInfo, "count" => count($usersInfo));
        }
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }

    public function actionGetAllUserRank()
    {
        //{"offset":0,"count":100,"size":128,"deviceCode":"AAAAA8888-001"}
        $result = null;
        $usersInfo = array();
        $userInList = false;
        $jsonObj = Trans::readJsonPost();
        parent::llog(json_encode($jsonObj), "Shooter.GetUserRank.PostData");
        $offset = 0;
        $count = 100;
        $size = 64;
        if (isset($jsonObj->offset)) {
            $offset = $jsonObj->offset;
        }
        if (isset($jsonObj->count)) {
            $count = $jsonObj->count;
        }
        if (isset($jsonObj->size)) {
            $size = $jsonObj->size;
        }
        if (isset($jsonObj->deviceCode)) {
            $devices = UserService::getInstance()->getUserRank($offset, $count);
            $u = UserService::getInstance()->getUserByDevice($jsonObj->deviceCode);
            $friendIds = array();
            $deja_id = -1;
            if (isset($u)) {
                $deja_id = $u->deja_id;
            }
            $friendIds = UserService::getInstance()->getFriendIds($deja_id, $jsonObj->deviceCode);
            if (is_array($devices)) {
                if (isset($jsonObj->deviceCode)) {
                    if (in_array($jsonObj->deviceCode, $devices)) {
                        $userInList = true;
                    }
                }
                $usersInfo = UserService::getInstance()->getUsersRankFromDevices($devices, $size, $friendIds);
            }
            $result = array("status" => 1, "userInList" => $userInList, "usersInfo" => $usersInfo, "count" => count($usersInfo));

        } else {
            $result = array("status" => 0, "msg" => "need device code");
        }
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }


    public function actionTest()
    {
        $result = null;
        $jsonObj = Trans::readJsonPost();
        $d = array(
            "id" => 100032,
            "friendIds" => array("#2$%%$^$^^31000794", 100043)
        );
        var_dump(json_encode($d, JSON_UNESCAPED_SLASHES));
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }

    public function actionBuyItem()
    {
        //{"deviceCode":"AAAAA8888-001","itemId":0,"count":2,"type":1,"buyType":1,"receipt":"aa"}
        $result;
        $jsonObj = Trans::readJsonPost();
        parent::llog(json_encode($jsonObj), "Shooter.BuyItem.PostData");
        if (isset($jsonObj->deviceCode) && isset($jsonObj->itemId) && isset($jsonObj->type) && isset($jsonObj->buyType)) {
            if (isset($jsonObj->count)) {
                $count = $jsonObj->count;
            } else {
                $count = 1;
            }
            $user = UserService::getInstance()->findByDevice($jsonObj->deviceCode);
            if (isset($user)) {
                //$e = User::model()->findByPk(1);
                $buyReturn = $user->buyItem($jsonObj->itemId, $jsonObj->type, $jsonObj->buyType, $count, $jsonObj->receipt);
                if ($buyReturn == 0) {
                    $updateU = UserService::getInstance()->getUserByDevice($jsonObj->deviceCode);
                    $result = array("status" => 1, "user" => $updateU);
                } else if ($buyReturn == -1) {
                    $result = array("status" => 0, "msg" => "Not enough money");
                } else if ($buyReturn == -2) {
                    $result = array("status" => 0, "msg" => "item not find ,item id" . $jsonObj->itemId);
                } else if ($buyReturn == -3) {
                    $result = array("status" => 0, "msg" => "bundleId not find" . $jsonObj->itemId);
                } else {
                    $result = array("status" => 0, "msg" => "verify fail" . $jsonObj->itemId);
                }
            } else {
                $result = array("status" => 0, "msg" => "device isn't exists");
            }
        } else {
            $result = array("status" => 0, "msg" => "need deviceCode,itemId,type,buyType");
        }
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }

    public function actionGetItemList()
    {
        $result;
        $count;
        $offset;
        $jsonObj = Trans::readJsonPost();
        if (isset($jsonObj->count)) {
            $count = $jsonObj->count;
        } else {
            $count = 100;
        }
        if (isset($jsonObj->offset)) {
            $offset = $jsonObj->offset;
        } else {
            $offset = 0;
        }
        $items = ItemService::getInstance()->getItemList($offset, $count);
        $result = array("status" => 1, "data" => $items, "count" => count($items));
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }

    public function actionGetCoinsItemList()
    {
        $jsonObj = Trans::readJsonPost();
        if (isset($jsonObj->count)) {
            $count = $jsonObj->count;
        } else {
            $count = 100;
        }
        if (isset($jsonObj->offset)) {
            $offset = $jsonObj->offset;
        } else {
            $offset = 0;
        }
        $allItems = ItemService::getInstance()->getItemList(0, 100);
        $itemList = array();
        foreach ($allItems as $item) {
            if (($item->buy_type & ItemBuyTypeEnum::game_money) == $item->buy_type) {
                $itemList[] = $item;
            }
        }
        if (count($itemList) > $count) {
            $itemList = UtilityService::getInstance()->arrayForward($itemList, $offset, $count);
        }
        $result = array("status" => 1, "data" => $itemList, "count" => count($itemList));
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }

    public function actionGetGemsAndCashItemList()
    {
        $jsonObj = Trans::readJsonPost();
        if (isset($jsonObj->count)) {
            $count = $jsonObj->count;
        } else {
            $count = 100;
        }
        if (isset($jsonObj->offset)) {
            $offset = $jsonObj->offset;
        } else {
            $offset = 0;
        }
        $allItems = ItemService::getInstance()->getItemList(0, 100);
        $itemList = array();
        foreach ($allItems as $item) {
            if ((($item->buy_type & ItemBuyTypeEnum::real_money) == $item->buy_type) || (($item->buy_type & ItemBuyTypeEnum::cash) == $item->buy_type)) {
                $itemList[] = $item;
            }
        }
        if (count($itemList) > $count) {
            $itemList = UtilityService::getInstance()->arrayForward($itemList, $offset, $count);
        }
        $result = array("status" => 1, "data" => $itemList, "count" => count($itemList));
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }

    public function actionGetIAPItemList()
    {
        $jsonObj = Trans::readJsonPost();
        if (isset($jsonObj->count)) {
            $count = $jsonObj->count;
        } else {
            $count = 100;
        }
        if (isset($jsonObj->offset)) {
            $offset = $jsonObj->offset;
        } else {
            $offset = 0;
        }
        $allItems = ItemService::getInstance()->getItemList(0, 100);
        $itemList = array();
        foreach ($allItems as $item) {
            if ((($item->buy_type & ItemBuyTypeEnum::cash) == $item->buy_type)) {
                if (isset($item->properties) && is_string($item->properties)) {
                    $item->properties = json_decode($item->properties);
                }
                $itemList[] = $item;
            }
        }
        if (count($itemList) > $count) {
            $itemList = UtilityService::getInstance()->arrayForward($itemList, $offset, $count);
        }
        $result = array("status" => 1, "data" => $itemList, "count" => count($itemList));
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }

//    public function actionSetItem()
//    {
//        //{"id":100032,"name":"test","description":"for test","game_money":15,"real_money":5,"type":1,"properties":"{\"attack\":20,\"defend\":10}","token"}
//        $result;
//        $jsonObj = Trans::readJsonPost();
//        parent::llog(json_encode($jsonObj), "Shooter.SetItem.PostData");
//        if (isset($jsonObj->name)) {
//            $item = new Item();
//            if (isset($jsonObj->id)) {
//                $item = Item::model()->findByPk($jsonObj->id);
//            } else {
//                date_default_timezone_set('UTC');
//                $item->create_time = date('Y-m-d H:i:s', time());
//            }
//            if (isset($item)) {
//                if (isset($jsonObj->description)) $item->description = $jsonObj->description;
//                if (isset($jsonObj->game_money)) $item->game_money = $jsonObj->game_money;
//                if (isset($jsonObj->real_money)) $item->real_money = $jsonObj->real_money;
//                if (isset($jsonObj->type)) $item->type = $jsonObj->type;
//                if (isset($jsonObj->properties)) $item->properties = $jsonObj->properties;
//                $item->name = $jsonObj->name;
//                $item->save();
//                $item = Item::model()->findByPk($item->id);
//                ItemService::getInstance()->addGameItemKey($item->id, json_encode($item->attributes));
//                $result = array("status" => 1, "item" => $item->attributes);
//            } else {
//                $result = array("status" => 0, "msg" => "item not found.id:" + $jsonObj->id);
//            }
//        } else {
//            $result = array("status" => 0, "msg" => "invalid request");
//        }
//        $this->renderPartial('json', array(
//            'jsonArr' => $result,
//            'postdata' => $jsonObj,
//        ));
//    }

    public function actionRequestLife()
    {
        //{"senderId":100032,"":"receiverId",100197,"deviceCode":"AAAAA8888-001"}
        $result = null;
        $jsonObj = Trans::readJsonPost();
        if (isset($jsonObj->senderId) && isset($jsonObj->receiverId)) {
            $senderDevice = UserService::getInstance()->getDevice($jsonObj->senderId);
            $receiveDevice = UserService::getInstance()->getDevice($jsonObj->receiverId);
            $email = new Email();
            $email->type = EmailTypeEnum::requestLife;
            $email->sender_id = $jsonObj->senderId;
            $email->receiver_id = $jsonObj->receiverId;
            $email->sender_device = $senderDevice;
            $email->receiver_device = $receiveDevice;
            $email->is_enable = 1;
            date_default_timezone_set('UTC');
            $email->create_time = date('Y-m-d H:i:s', time());
            $email->save();
            ShooterService::getInstance()->setEmailExpire($email->id);
            $ret = UserService::getInstance()->pushDejaMessage($jsonObj->senderId, $jsonObj->receiverId, $jsonObj->deviceCode, Translate::tran("Give me life ,my friend", "en"));
            $result = array("status" => 1, "msg" => "request life success");
        } else {
            $result = array("status" => 0, "msg" => "need senderId and receiverId");
        }
        $this->renderPartial('jsonDev', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }

    public function actionSendLife()
    {
        //{"emailId":1,"deviceCode":"AAAAA8888-001"}
        $result = null;
        $jsonObj = Trans::readJsonPost();
        if (isset($jsonObj->emailId)) {

            $email = Email::model()->findByPk($jsonObj->emailId);
            if (!isset($email)) {
                $result = array("status" => 0, "msg" => "email not found");
            } else {
                if ($email->is_enable == 1) {
                    $email->is_enable = 0;
                    $email->save();
                    $new_email = new Email();
                    $new_email->sender_id = $email->receiver_id;
                    $new_email->receiver_id = $email->sender_id;
                    $new_email->sender_device = $email->receiver_device;
                    $new_email->receiver_device = $email->sender_device;
                    $new_email->type = EmailTypeEnum::receiveLife;
                    date_default_timezone_set('UTC');
                    $new_email->create_time = date('Y-m-d H:i:s', time());
                    $new_email->save();
                    ShooterService::getInstance()->setEmailExpire($new_email->id);
                    $ret = UserService::getInstance()->pushDejaMessage($new_email->sender_id, $new_email->receiver_id, $jsonObj->deviceCode, Translate::tran("You have receive a new life", "en"));
                }
                $result = array("status" => 1, "msg" => "send life success");
            }
        } else {
            $result = array("status" => 0, "msg" => "need emailId");
        }

        $this->renderPartial('jsonDev', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }

    public function actionReceiveLife()
    {
        //{"emailId":1}
        $result = null;
        $jsonObj = Trans::readJsonPost();
        if (isset($jsonObj->emailId)) {

            $email = Email::model()->findByPk($jsonObj->emailId);
            if (!isset($email)) {
                $result = array("status" => 0, "msg" => "email not found");
            } else if ($email->type != EmailTypeEnum::receiveLife) {
                $result = array("status" => 0, "msg" => "invalid request");
            } else {
                if ($email->is_enable == 1) {
                    $email->is_enable = 0;
                    $email->save();
                }
                $result = array("status" => 1, "msg" => "receive life success");
            }
        } else {
            $result = array("status" => 0, "msg" => "need emailId");
        }

        $this->renderPartial('jsonDev', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }

    public function actionSendGift()
    {
        //{"senderId":100032,"receiverId":100197,"itemId":1,"itemType":1}
        $result = null;
        $jsonObj = Trans::readJsonPost();

        if (isset($jsonObj->senderId) && isset($jsonObj->receiverId) && isset($jsonObj->itemId) && isset($jsonObj->itemType)) {
            $senderDevice = UserService::getInstance()->getDevice($jsonObj->senderId);
            $receiveDevice = UserService::getInstance()->getDevice($jsonObj->receiverId);
            $email = new Email();
            $email->type = EmailTypeEnum::receiveGift;
            $email->sender_id = $jsonObj->senderId;
            $email->receiver_id = $jsonObj->receiverId;
            $email->sender_device = $senderDevice;
            $email->receiver_device = $receiveDevice;
            $email->is_enable = 1;
            $email->item_id = (int)$jsonObj->itemId;
            $email->item_type = (int)$jsonObj->itemType;
            date_default_timezone_set('UTC');
            $email->create_time = date('Y-m-d H:i:s', time());
            $email->save();
            ShooterService::getInstance()->setEmailExpire($email->id);
            $result = array("status" => 1, "msg" => "Send gift success");
        } else {
            $result = array("status" => 0, "msg" => "need senderId and receiverId");
        }
        $this->renderPartial('jsonDev', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }


    public function actionReceiveGift()
    {
        //{"emailId":1}
        $result = null;
        $jsonObj = Trans::readJsonPost();
        if (isset($jsonObj->emailId)) {

            $email = Email::model()->findByPk($jsonObj->emailId);
            if (!isset($email)) {
                $result = array("status" => 0, "msg" => "email not found");
            } else if ($email->type != EmailTypeEnum::receiveGift) {
                $result = array("status" => 0, "msg" => "invalid request");
            } else {
                if ($email->is_enable == 1) {
                    $email->is_enable = 0;
                    $email->save();
                }
                $result = array("status" => 1, "msg" => "receive gift success");
            }
        } else {
            $result = array("status" => 0, "msg" => "need emailId");
        }
        $this->renderPartial('jsonDev', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }

    public function actionGetEmailList()
    {
        //{"dejaId":1,"size":64,"deviceCode":"asss","offset":0,"count":20}
        $result = null;
        $jsonObj = Trans::readJsonPost();
        $dejaId = -1;
        $size = 64;
        if (isset($jsonObj->size)) {
            $size = $jsonObj->size;
        }
        if (isset($jsonObj->dejaId)) {
            $dejaId = $jsonObj->dejaId;
        } else if (isset($jsonObj->deviceCode)) {
            $user = UserService::getInstance()->getUserByDevice($jsonObj->deviceCode);
            $dejaId = $user->deja_id;
        }
        if ($dejaId == -1) {
            $result = array("status" => 0, "msg" => "invalid user");
        } else {
            $criteria = new CDbCriteria;
            $criteria->addCondition("is_enable=1");
            $criteria->addCondition("receiver_id=:receiver_id");
            $criteria->params[':receiver_id'] = $dejaId;
            $criteria->order = 'id DESC';
            if (isset($jsonObj->offset)) {
                $criteria->offset = $jsonObj->offset;
            }
            if (isset($jsonObj->count)) {
                $criteria->limit = $jsonObj->count;
            }
            $emailList = Email::model()->findAll($criteria);
            $data = array();
            foreach ($emailList as $email) {
                if (ShooterService::getInstance()->isEmailValid($email->id)) {
                    $item = array();
                    $item["id"] = (int)$email->id;
                    $senderM = UserService::getInstance()->getFriendDejaModel($email->sender_id, $size);
                    $receiverM = UserService::getInstance()->getFriendDejaModel($email->receiver_id, $size);
                    $item["sender"] = array("id" => (int)$email->sender_id, "device" => $email->sender_device, "name" => $senderM->name, "avatar" => $senderM->avatar, "avatar_head" => $senderM->avatar_head);
                    $item["receiver"] = array("id" => (int)$email->receiver_id, "device" => $email->receiver_device, "name" => $receiverM->name, "avatar" => $receiverM->avatar, "avatar_head" => $receiverM->avatar_head);
                    $item["type"] = (int)$email->type;
                    $item["item_id"] = (int)$email->item_id;
                    $item["item_type"] = (int)$email->item_type;
                    $item["expire"] = ShooterService::getInstance()->getTimeLeftOfEmail($email->id);
                    switch ($item["type"]) {
                        case EmailTypeEnum::receiveGift:
                            $item["title"] = Translate::tran("You got a present!", "en");
                            $item["content"] = Translate::tran("gave you a gift!", "en");
                            break;
                        case EmailTypeEnum::receiveLife:
                            $item["title"] = Translate::tran("You got a present!", "en");
                            $item["content"] = Translate::tran("gave you a life!", "en");
                            break;
                        case EmailTypeEnum::requestLife:
                            $item["title"] = Translate::tran("Help out your friend!", "en");
                            $item["content"] = Translate::tran("asks you to send a life!", "en");
                            break;
                    }
                    array_push($data, $item);
                } else {
                    $email->is_enable = 0;
                    $email->save();
                }
            }
            $result = array("status" => 1, "data" => $data, "count" => count($data));
        }
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }

    public function actionOnEnterGame()
    {
        $result = null;
        $jsonObj = Trans::readJsonPost();
        //{"items":[{"itemId":3,"type":0,"count":3},{"itemId":2,"type":0,"count":1}],"deviceCode":"Axkas-192365-eeaeee"}
        if (isset($jsonObj->items) && is_array($jsonObj->items) && isset($jsonObj->deviceCode)) {
            $user = UserService::getInstance()->findByDevice($jsonObj->deviceCode);
            $hasEnough = true;
            foreach ($jsonObj->items as $item) {
                if (!$user->hasEnoughItem($item)) {
                    $hasEnough = false;
                    break;
                }
            }
            if ($hasEnough) {
                foreach ($jsonObj->items as $item) {
                    $user = $user->exhaustItem($item);
                }
                $result = array("status" => 1, "user" => $user);
            } else {
                $modelArr = $user->attributes;
                array_walk_recursive($modelArr, function (&$item, $key) {
                    if (is_numeric($item)) {
                        $item = (int)$item;
                    }
                });
                $result = array("status" => 0, "msg" => "not enough items", "user" => $modelArr);
            }
        } else {
            $result = array("status" => 0, "msg" => "need items");
        }
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }


    public function filterss()
    {
        return array(
            'postOnly - LoadSetting',
            array(
                'application.filters.AccessFilter - LoadSetting',
            ),
        );
    }
}